import React, { useEffect, useRef, useState } from "react";
import { showToast } from '@tarojs/taro'
import CustomTabBar from '../../components/CustomTabBar'

const Ditu: React.FC = () => {
  const mapRef = useRef<HTMLDivElement>(null);
  const mapInstanceRef = useRef<any>(null);
  const [zoomLevel, setZoomLevel] = useState(15);
  const [searchValue, setSearchValue] = useState("");
  const [targetLocation, setTargetLocation] = useState<{ lng: number, lat: number, name: string } | null>(null);
  const [currentLocation, setCurrentLocation] = useState<{ lng: number, lat: number } | null>(null);
  const [isNavigating, setIsNavigating] = useState(false);
  const [showTraffic, setShowTraffic] = useState(false);
  // 新增：搜索周边门店的状态
  const [isSearchingStores, setIsSearchingStores] = useState(false);
  // 新增：选中的门店索引
  const [selectedStoreIndex, setSelectedStoreIndex] = useState<number | null>(null);
  const routeRef = useRef<any>(null);
  const trafficLayerRef = useRef<any>(null);
  // 新增：存储门店标记的引用
  const storeMarkersRef = useRef<any[]>([]);
  // 新增：存储导航标记的引用
  const navigationMarkersRef = useRef<any[]>([]);

  // 新增：聚合相关状态
  const [useCluster, setUseCluster] = useState(false);
  const [clusterStyle, setClusterStyle] = useState(0); // 0: 默认样式, 1: 自定义图标, 2: 完全自定义
  const clusterRef = useRef<any>(null);
  const [storeData, setStoreData] = useState<any[]>([]);

  useEffect(() => {
    function initAMap() {
      if ((window as any).AMap && mapRef.current) {
        // @ts-ignore
        const map = new window.AMap.Map(mapRef.current, {
          center: [116.397428, 39.90923],
          zoom: 15
        });

        mapInstanceRef.current = map;
        setZoomLevel(map.getZoom());
        let circle: any = null;
        let lastPosition: any = null;

        // 初始化实时路况图层
        (window as any).AMap.plugin('AMap.TileLayer.Traffic', function () {
          const trafficLayer = new ((window as any).AMap).TileLayer.Traffic({
            zIndex: 10,
            opacity: 0.8
          });
          trafficLayerRef.current = trafficLayer;
        });

        (window as any).AMap.plugin('AMap.Geolocation', function () {
          const geolocation = new ((window as any).AMap).Geolocation({
            enableHighAccuracy: true,
            timeout: 10000,
            buttonPosition: 'RB',
            showMarker: true,
            showCircle: false,
            panToLocation: true,
            zoomToAccuracy: true,
            useNative: false
          });
          map.addControl(geolocation);
          geolocation.getCurrentPosition(function (status, result) {
            if (status === 'complete' && result.position) {
              map.setZoomAndCenter(18, result.position);
              const currentPos = {
                lng: result.position.lng,
                lat: result.position.lat
              };
              setCurrentLocation(currentPos);
              
              // 自动搜索周边门店
              console.log('定位成功，自动搜索周边门店...');
              searchNearbyStoresAuto(currentPos);
            } else {
              const defaultPos = [116.397428, 39.90923];
              map.setZoomAndCenter(15, defaultPos);
              console.log('定位失败，使用默认位置');
            }
          });
        });

        map.on('zoomend', function () {
          setZoomLevel(map.getZoom());
          if (circle) { map.remove(circle); circle = null; }
          if (map.getZoom() > 14 && lastPosition) {
            circle = new ((window as any).AMap).Circle({
              center: lastPosition,
              radius: 30,
              fillColor: '#80d8ff',
              strokeColor: '#0091ea',
              strokeWeight: 2,
              fillOpacity: 0.3,
              bubble: false,
              zIndex: 1
            });
            map.add(circle);
          }
        });
      }
    }

    if (document.getElementById("amap-script")) {
      if ((window as any).AMap && mapRef.current) {
        initAMap();
      } else {
        const timer = setInterval(() => {
          if ((window as any).AMap && mapRef.current) {
            clearInterval(timer);
            initAMap();
          }
        }, 100);
      }
      return;
    }
    const script = document.createElement("script");
    script.id = "amap-script";
    script.type = "text/javascript";
    script.src = "https://webapi.amap.com/maps?v=2.0&key=3511e577cbfbd0a503fd118ede3acbc2&plugin=AMap.MarkerCluster";
    script.onload = () => {
      initAMap();
    };
    document.body.appendChild(script);
  }, []);

  // 新增：聚合样式配置
  const getClusterConfig = (style: number) => {
    const gridSize = 60;
    
    if (style === 2) { // 完全自定义
      const _renderClusterMarker = function (context: any) {
        // 修复：防止除零错误，确保storeData.length大于0
        const totalStores = storeData && storeData.length > 0 ? storeData.length : 1;
        const factor = Math.pow(context.count / totalStores, 1 / 18);
        const div = document.createElement('div');
        const Hue = 180 - factor * 180;
        const bgColor = 'hsla(' + Hue + ',100%,40%,0.7)';
        const fontColor = 'hsla(' + Hue + ',100%,90%,1)';
        const borderColor = 'hsla(' + Hue + ',100%,40%,1)';
        const shadowColor = 'hsla(' + Hue + ',100%,90%,1)';
        div.style.backgroundColor = bgColor;
        // 修复：防止除零错误
        const size = Math.round(30 + Math.pow(context.count / totalStores, 1 / 5) * 20);
        div.style.width = div.style.height = size + 'px';
        div.style.border = 'solid 1px ' + borderColor;
        div.style.borderRadius = size / 2 + 'px';
        div.style.boxShadow = '0 0 5px ' + shadowColor;
        div.innerHTML = context.count;
        div.style.lineHeight = size + 'px';
        div.style.color = fontColor;
        div.style.fontSize = '14px';
        div.style.textAlign = 'center';
        context.marker.setOffset(new ((window as any).AMap).Pixel(-size / 2, -size / 2));
        context.marker.setContent(div);
      };
      
      const _renderMarker = function(context: any) {
        const content = '<div style="background-color: hsla(180, 100%, 50%, 0.3); height: 18px; width: 18px; border: 1px solid hsl(180, 100%, 40%); border-radius: 12px; box-shadow: hsl(180, 100%, 50%) 0px 0px 3px;"></div>';
        const offset = new ((window as any).AMap).Pixel(-9, -9);
        context.marker.setContent(content);
        context.marker.setOffset(offset);
      };
      
      return {
        gridSize: gridSize,
        renderClusterMarker: _renderClusterMarker,
        renderMarker: _renderMarker,
      };
    } else if (style === 1) { // 自定义图标
      const sts = [{
        url: "//a.amap.com/jsapi_demos/static/images/blue.png",
        size: new ((window as any).AMap).Size(32, 32),
        offset: new ((window as any).AMap).Pixel(-16, -16)
      }, {
        url: "//a.amap.com/jsapi_demos/static/images/green.png",
        size: new ((window as any).AMap).Size(32, 32),
        offset: new ((window as any).AMap).Pixel(-16, -16)
      }, {
        url: "//a.amap.com/jsapi_demos/static/images/orange.png",
        size: new ((window as any).AMap).Size(36, 36),
        offset: new ((window as any).AMap).Pixel(-18, -18)
      }, {
        url: "//a.amap.com/jsapi_demos/static/images/red.png",
        size: new ((window as any).AMap).Size(48, 48),
        offset: new ((window as any).AMap).Pixel(-24, -24)
      }, {
        url: "//a.amap.com/jsapi_demos/static/images/darkRed.png",
        size: new ((window as any).AMap).Size(48, 48),
        offset: new ((window as any).AMap).Pixel(-24, -24)
      }];
      
      return {
        styles: sts,
        gridSize: gridSize
      };
    } else { // 默认样式
      return { gridSize: gridSize };
    }
  };

  // 新增：创建聚合
  const createCluster = (points: any[]) => {
    if (!mapInstanceRef.current || !(window as any).AMap) return;
    
    // 清除旧聚合
    if (clusterRef.current) {
      clusterRef.current.setMap(null);
      clusterRef.current = null;
    }
    
    // 创建新聚合
    const config = getClusterConfig(clusterStyle);
    const cluster = new ((window as any).AMap).MarkerCluster(mapInstanceRef.current, points, config);
    clusterRef.current = cluster;
    
    console.log(`聚合创建完成，样式: ${clusterStyle === 0 ? '默认' : clusterStyle === 1 ? '自定义图标' : '完全自定义'}`);
  };

  // 修改：处理标记点击事件的函数
  const handleMarkerClick = (marker: any, store: any, index: number) => {
    // 先将所有标记重置为红色
    storeMarkersRef.current.forEach((existingMarker) => {
      existingMarker.setIcon(new ((window as any).AMap).Icon({
        size: new ((window as any).AMap).Size(25, 34),
        image: 'https://webapi.amap.com/theme/v1.3/markers/n/mark_r.png'
      }));
    });
    
    const [lng, lat] = store.location.split(',').map(Number);
    const distance = store.distance ? `${(store.distance / 1000).toFixed(2)}km` : '未知距离';
    
    // 如果点击的是当前选中的标记，启动导航
    if (selectedStoreIndex === index) {
      // 先清除旧路线
      if (routeRef.current && mapInstanceRef.current) {
        mapInstanceRef.current.remove(routeRef.current);
        routeRef.current = null;
      }
      
      // 设置目标位置并启动导航
      setTargetLocation({
        lng: lng,
        lat: lat,
        name: store.name
      });
      
      // 调用导航功能
      handleNavigation();
      
      setSelectedStoreIndex(null);
    } else {
      // 先清除旧路线
      if (routeRef.current && mapInstanceRef.current) {
        mapInstanceRef.current.remove(routeRef.current);
        routeRef.current = null;
      }
      // 设置目标位置
      setTargetLocation({
        lng: lng,
        lat: lat,
        name: store.name
      });
      // 将当前点击的标记变为蓝色
      setSelectedStoreIndex(index);
      marker.setIcon(new ((window as any).AMap).Icon({
        size: new ((window as any).AMap).Size(25, 34),
        image: 'https://webapi.amap.com/theme/v1.3/markers/n/mark_b.png'
      }));
    }
    
    // 显示信息窗口
    const infoWindow = new ((window as any).AMap).InfoWindow({
      content: `
        <div style="padding: 6px; min-width: 100px; max-width: 150px; font-family: Arial, sans-serif;">
          <h3 style="margin: 0 0 4px 0; color: #333; font-size: 13px; font-weight: bold;">🔧 ${store.name}</h3>
          <p style="margin: 2px 0; color: #666; font-size: 11px; line-height: 1.3;"><strong>地址:</strong> ${store.address || '地址未知'}</p>
          <p style="margin: 2px 0; color: #666; font-size: 11px; line-height: 1.3;"><strong>距离:</strong> ${distance}</p>
          ${store.tel ? `<p style="margin: 2px 0; color: #666; font-size: 11px; line-height: 1.3;"><strong>电话:</strong> ${store.tel}</p>` : ''}
          ${store.business_area ? `<p style="margin: 2px 0; color: #666; font-size: 11px; line-height: 1.3;"><strong>商圈:</strong> ${store.business_area}</p>` : ''}
          ${store.rating ? `<p style="margin: 2px 0; color: #666; font-size: 11px; line-height: 1.3;"><strong>评分:</strong> ${store.rating}</p>` : ''}
          ${selectedStoreIndex === index ? '<p style="margin: 4px 0 2px 0; color: #007bff; font-size: 11px; font-weight: bold; line-height: 1.3;">💡 再次点击开始导航</p>' : ''}
        </div>
      `,
      offset: new ((window as any).AMap).Pixel(0, -30)
    });
    infoWindow.open(mapInstanceRef.current, [lng, lat]);
  };

  // 修改：自动搜索周边门店（定位成功后自动调用）
  const searchNearbyStoresAuto = async (location: { lng: number, lat: number }) => {
    console.log('🔍 === 开始自动搜索周边电子产品维修门店 ===');
    console.log('当前位置:', location);
    
    try {
      const apiUrl = `https://restapi.amap.com/v3/place/around?key=3511e577cbfbd0a503fd118ede3acbc2&location=${location.lng},${location.lat}&keywords=电子产品维修|手机维修|电脑维修|数码维修&types=060000&radius=5000&offset=20&page=1&extensions=all`;
      console.log('请求URL:', apiUrl);
      
      const response = await fetch(apiUrl);
      const data = await response.json();
      
      console.log('API返回数据:', data);
      
      // 修复：添加数据验证，防止访问undefined的length属性
      if (data.status === '1' && data.pois && Array.isArray(data.pois) && data.pois.length > 0) {
        // 保存门店数据
        setStoreData(data.pois);
        
        // 清除旧的标记和聚合
        if (storeMarkersRef.current && storeMarkersRef.current.length > 0 && mapInstanceRef.current) {
          mapInstanceRef.current.remove(storeMarkersRef.current);
          storeMarkersRef.current = [];
        }
        
        if (clusterRef.current) {
          clusterRef.current.setMap(null);
          clusterRef.current = null;
        }
        
        if (useCluster) {
          // 使用聚合模式
          const points = data.pois.map((store: any, index: number) => {
            const [lng, lat] = store.location.split(',').map(Number);
            return {
              lnglat: [lng, lat],
              name: store.name,
              address: store.address,
              distance: store.distance,
              tel: store.tel,
              type: store.type,
              business_area: store.business_area,
              rating: store.rating,
              storeIndex: index,
              storeData: store
            };
          });
          createCluster(points);
        } else {
          // 使用原有标记模式
          const newMarkers: any[] = [];
          
          data.pois.forEach((store: any, index: number) => {
            if (store.location) {
              const [lng, lat] = store.location.split(',').map(Number);
              const distance = store.distance ? `${(store.distance / 1000).toFixed(2)}km` : '距离未知';
              
              console.log(`\n📍 门店 ${index + 1}: ${store.name}`);
              console.log(`   地址: ${store.address || '地址未知'}`);
              console.log(`   距离: ${distance}`);
              console.log(`   电话: ${store.tel || '电话未知'}`);
              console.log(`   类型: ${store.type || '类型未知'}`);
              console.log(`   商圈: ${store.business_area || '商圈未知'}`);
              console.log(`   评分: ${store.rating || '暂无评分'}`);
              console.log(`   坐标: ${lng}, ${lat}`);
              
              const marker = new ((window as any).AMap).Marker({
                position: [lng, lat],
                title: `${store.name}\n地址: ${store.address || '地址未知'}\n距离: ${distance}\n电话: ${store.tel || '电话未知'}`,
                icon: new ((window as any).AMap).Icon({
                  size: new ((window as any).AMap).Size(25, 34),
                  image: 'https://webapi.amap.com/theme/v1.3/markers/n/mark_r.png'
                }),
                offset: new ((window as any).AMap).Pixel(-12, -34)
              });
              
              // 添加点击事件
              marker.on('click', function() {
                handleMarkerClick(marker, store, index);
              });
              
              newMarkers.push(marker);
            }
          });
          
          // 将所有标记添加到地图
          if (newMarkers.length > 0 && mapInstanceRef.current) {
            mapInstanceRef.current.add(newMarkers);
            storeMarkersRef.current = newMarkers;
            console.log(`\n📍 === 已在地图上标记 ${newMarkers.length} 家维修店（红色标记，点击可变绿色选中） ===`);
          }
        }
        
        console.log(`\n🎉 === 搜索完成！共找到 ${data.pois.length} 家电子产品维修门店，详细信息已在上方显示 ===`);
        
        // 按距离排序并显示最近的5家
        const sortedStores = data.pois
          .filter((store: any) => store.distance)
          .sort((a: any, b: any) => parseInt(a.distance) - parseInt(b.distance))
          .slice(0, 5);
          
        console.log('\n🏆 === 距离您最近的5家电子产品维修门店 ===');
        sortedStores.forEach((store: any, index: number) => {
          const distance = (store.distance / 1000).toFixed(2);
          console.log(`${index + 1}. ${store.name} - ${distance}km - ${store.address}`);
        });
        
      } else {
        console.log('❌ 搜索结果为空或搜索失败');
        console.log('API返回状态:', data.status);
        console.log('错误信息:', data.info);
        console.log('返回的pois数据:', data.pois);
        
        // 如果没有数据，清空之前的状态
        setStoreData([]);
      }
      
    } catch (error) {
      console.error('❌ 搜索电子产品维修门店时发生错误:', error);
      // 发生错误时也清空状态
      setStoreData([]);
    }
  };

  // 新增：切换聚合模式
  const toggleCluster = () => {
    setUseCluster(!useCluster);
    // 重新渲染当前数据
    if (storeData.length > 0 && currentLocation) {
      searchNearbyStoresAuto(currentLocation);
    }
  };

  // 新增：切换聚合样式
  const changeClusterStyle = (style: number) => {
    setClusterStyle(style);
    // 重新创建聚合
    if (useCluster && storeData.length > 0) {
      const points = storeData.map((store: any, index: number) => {
        const [lng, lat] = store.location.split(',').map(Number);
        return {
          lnglat: [lng, lat],
          name: store.name,
          address: store.address,
          distance: store.distance,
          tel: store.tel,
          type: store.type,
          business_area: store.business_area,
          rating: store.rating,
          storeIndex: index,
          storeData: store
        };
      });
      createCluster(points);
    }
  };

  const handleSearch = async () => {
    console.log('开始搜索:', searchValue);

    if (!searchValue) {
      showToast({ title:'请输入搜索内容',icon:'none' });    
      return;
    }

    try {
      const apiUrl = `https://restapi.amap.com/v3/geocode/geo?key=3511e577cbfbd0a503fd118ede3acbc2&address=${encodeURIComponent(searchValue)}`;
      console.log('请求URL:', apiUrl);

      const response = await fetch(apiUrl);
      const data = await response.json();

      console.log('API返回数据:', data);

      if (data.status === '1' && data.geocodes && data.geocodes.length > 0) {
        const geocode = data.geocodes[0];
        const [lng, lat] = geocode.location.split(',').map(Number);

        console.log(1111);
        console.log('找到坐标:', lng, lat);

        setTargetLocation({
          lng,
          lat,
          name: geocode.formatted_address || searchValue
        });

        if (mapInstanceRef.current) {
          console.log('开始跳转地图到:', [lng, lat]);

          mapInstanceRef.current.setZoomAndCenter(16, [lng, lat]);

          const marker = new ((window as any).AMap).Marker({
            position: [lng, lat],
            title: geocode.formatted_address || searchValue
          });

          mapInstanceRef.current.add(marker);

          console.log('地图跳转完成');
        } else {
          console.error('地图实例未找到');
          showToast({ title:'地图未初始化完成，请稍后再试',icon:'none' });
        }
      } else {
        console.log('搜索失败，状态:', data.status, '结果:', data);
        showToast({ title:`搜索失败: ${data.info || '未知错误'}`,icon:'none' });
      }
    } catch (error) {
      console.error('网络请求失败:', error);
      showToast({ title:'网络请求失败，请检查网络连接',icon:'none' });
    }
  };

  // 修改导航功能，考虑实时路况
  const handleNavigation = async () => {
    if (!targetLocation) {
      showToast({ title:'请先搜索目标地点',icon:'none' });
      return;
    }

    if (!currentLocation) {
      showToast({ title:'正在获取当前位置，请稍后再试',icon:'none' });
      if (mapInstanceRef.current && (window as any).AMap) {
        (window as any).AMap.plugin('AMap.Geolocation', function () {
          const geolocation = new ((window as any).AMap).Geolocation({
            enableHighAccuracy: true,
            timeout: 10000,
            useNative: false
          });
          geolocation.getCurrentPosition(function (status, result) {
            if (status === 'complete' && result.position) {
              setCurrentLocation({
                lng: result.position.lng,
                lat: result.position.lat
              });
              showToast({ title:'位置获取成功，请再次点击导航',icon:'success' });
            } else {
              showToast({ title:'无法获取当前位置，请检查定位权限',icon:'none' });  
            }
          });
        });
      }
      return;
    }

    setIsNavigating(true);

    try {
      // 路径规划时考虑实时路况
      const routeUrl = `https://restapi.amap.com/v3/direction/driving?key=3511e577cbfbd0a503fd118ede3acbc2&origin=${currentLocation.lng},${currentLocation.lat}&destination=${targetLocation.lng},${targetLocation.lat}&extensions=all&strategy=0`; // strategy=0 表示考虑实时路况的最快路径

      console.log('路径规划请求URL:', routeUrl);

      const response = await fetch(routeUrl);
      const data = await response.json();

      console.log('路径规划返回数据:', data);

      if (data.status === '1' && data.route && data.route.paths && data.route.paths.length > 0) {
        const path = data.route.paths[0];
        const steps = path.steps;

        if (routeRef.current && mapInstanceRef.current) {
          mapInstanceRef.current.remove(routeRef.current);
        }

        const routeCoords: [number, number][] = [];
        steps.forEach((step: any) => {
          const polyline = step.polyline;
          const coords = polyline.split(';').map((point: string) => {
            const [lng, lat] = point.split(',').map(Number);
            return [lng, lat] as [number, number];
          });
          routeCoords.push(...coords);
        });

        if (mapInstanceRef.current && (window as any).AMap) {
          // 清除旧的导航标记
          if (navigationMarkersRef.current.length > 0) {
            mapInstanceRef.current.remove(navigationMarkersRef.current);
            navigationMarkersRef.current = [];
          }

          const polyline = new ((window as any).AMap).Polyline({
            path: routeCoords,
            strokeColor: '#3366FF',
            strokeWeight: 6,
            strokeOpacity: 0.8,
            strokeStyle: 'solid'
          });

          mapInstanceRef.current.add(polyline);
          routeRef.current = polyline;

          mapInstanceRef.current.setFitView([polyline]);

          const startMarker = new ((window as any).AMap).Marker({
            position: [currentLocation.lng, currentLocation.lat],
            title: '起点',
            icon: new ((window as any).AMap).Icon({
              size: new ((window as any).AMap).Size(25, 34),
              image: 'https://webapi.amap.com/theme/v1.3/markers/n/start.png'
            })
          });

          const endMarker = new ((window as any).AMap).Marker({
            position: [targetLocation.lng, targetLocation.lat],
            title: '终点',
            icon: new ((window as any).AMap).Icon({
              size: new ((window as any).AMap).Size(25, 34),
              image: 'https://webapi.amap.com/theme/v1.3/markers/n/end.png'
            })
          });

          mapInstanceRef.current.add([startMarker, endMarker]);
          // 保存导航标记引用
          navigationMarkersRef.current = [startMarker, endMarker];

          const distance = (path.distance / 1000).toFixed(1);
          const duration = Math.round(path.duration / 60);
          const traffic = path.traffic_lights ? `，途经${path.traffic_lights}个红绿灯` : '';

          // showToast(`导航路线规划成功！\n距离：${distance}公里\n预计时间：${duration}分钟${traffic}\n\n路线已在地图上显示（已考虑实时路况）。`);
        }
      } else {
        console.log('路径规划失败:', data);
        showToast({ title:`路径规划失败: ${data.info || '未知错误'}`,icon:'none' });
      }
    } catch (error) {
      console.error('路径规划请求失败:', error);
      showToast({ title:'路径规划失败，请检查网络连接',icon:'none' });
    } finally {
      setIsNavigating(false);
    }
  };

  const clearRoute = () => {
    if (routeRef.current && mapInstanceRef.current) {
      mapInstanceRef.current.remove(routeRef.current);
      routeRef.current = null;
    }
    
    // 清除导航标记
    if (navigationMarkersRef.current.length > 0 && mapInstanceRef.current) {
      mapInstanceRef.current.remove(navigationMarkersRef.current);
      navigationMarkersRef.current = [];
    }
    
    showToast({ title:'导航路线已清除',icon:'success' });
  };

  // 新增：切换实时路况显示
  const toggleTraffic = () => {
    if (!mapInstanceRef.current || !trafficLayerRef.current) {
      showToast({ title:'地图未初始化完成',icon:'none' });
      return;
    }

    if (showTraffic) {
      // 隐藏路况
      mapInstanceRef.current.remove(trafficLayerRef.current);
      setShowTraffic(false);
      showToast({ title:'实时路况已关闭',icon:'success' });
    } else {
      // 显示路况
      mapInstanceRef.current.add(trafficLayerRef.current);
      setShowTraffic(true);
      showToast({ title:'实时路况已开启',icon:'success' });
    }
  };

  return (
    <div style={{ position: 'relative', width: '100%', height: '100vh' }}>
      {/* 移动端适配的控制面板 */}
      <div style={{
        position: 'absolute',
        top: '10px',
        left: '10px',
        right: '10px',
        zIndex: 1000,
        background: '#fff',
        padding: '12px',
        borderRadius: '12px',
        boxShadow: '0 4px 12px rgba(0,0,0,0.15)',
        display: 'flex',
        flexDirection: 'column',
        gap: '12px'
      }}>
        {/* 搜索栏 */}
        <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
          <input
            type="text"
            value={searchValue}
            onChange={e => setSearchValue(e.target.value)}
            placeholder="请输入地址"
            style={{
              flex: 1,
              padding: '12px 16px',
              borderRadius: '8px',
              border: '1px solid #ddd',
              fontSize: '16px',
              outline: 'none'
            }}
          />
          <button
            onClick={handleSearch}
            style={{
              padding: '12px 20px',
              borderRadius: '8px',
              border: 'none',
              background: '#1976d2',
              color: '#fff',
              cursor: 'pointer',
              fontSize: '16px',
              fontWeight: 'bold',
              minWidth: '80px'
            }}
          >
            搜索
          </button>
        </div>

        {/* 功能按钮组 */}
        <div style={{ display: 'flex', gap: '8px', flexWrap: 'wrap' }}>
          <button
            onClick={toggleTraffic}
            style={{
              flex: 1,
              minWidth: '120px',
              padding: '10px 16px',
              borderRadius: '8px',
              border: 'none',
              background: showTraffic ? '#ff9800' : '#2196f3',
              color: '#fff',
              cursor: 'pointer',
              fontSize: '14px',
              fontWeight: 'bold'
            }}
          >
            {showTraffic ? '🚦 关闭路况' : '🚦 显示路况'}
          </button>
          
          <button
            onClick={toggleCluster}
            style={{
              flex: 1,
              minWidth: '120px',
              padding: '10px 16px',
              borderRadius: '8px',
              border: 'none',
              background: useCluster ? '#4caf50' : '#9e9e9e',
              color: '#fff',
              cursor: 'pointer',
              fontSize: '14px',
              fontWeight: 'bold'
            }}
          >
            {useCluster ? '📍 关闭聚合' : '📍 开启聚合'}
          </button>
        </div>

        {/* 聚合样式选择 */}
        {useCluster && (
          <div style={{ display: 'flex', gap: '6px', flexWrap: 'wrap' }}>
            {['默认', '图标', '自定义'].map((style, index) => (
              <button
                key={index}
                onClick={() => changeClusterStyle(index)}
                style={{
                  flex: 1,
                  minWidth: '80px',
                  padding: '8px 12px',
                  borderRadius: '6px',
                  border: 'none',
                  background: clusterStyle === index ? '#673ab7' : '#e0e0e0',
                  color: clusterStyle === index ? '#fff' : '#333',
                  cursor: 'pointer',
                  fontSize: '12px',
                  fontWeight: 'bold'
                }}
              >
                {style}
              </button>
            ))}
          </div>
        )}

        {/* 位置信息 */}
        {(currentLocation || targetLocation) && (
          <div style={{ 
            fontSize: '12px', 
            color: '#666',
            background: '#f5f5f5',
            padding: '8px',
            borderRadius: '6px'
          }}>
            {currentLocation && (
              <div>📍 当前：{currentLocation.lng.toFixed(4)}, {currentLocation.lat.toFixed(4)}</div>
            )}
            {targetLocation && (
              <div>🎯 目标：{targetLocation.name}</div>
            )}
          </div>
        )}

        {/* 导航控制 */}
        {targetLocation && (
          <div style={{ display: 'flex', gap: '8px' }}>
            <button
              onClick={handleNavigation}
              disabled={isNavigating}
              style={{
                flex: 2,
                padding: '12px 16px',
                borderRadius: '8px',
                border: 'none',
                background: isNavigating ? '#ccc' : '#4caf50',
                color: '#fff',
                cursor: isNavigating ? 'not-allowed' : 'pointer',
                fontSize: '16px',
                fontWeight: 'bold'
              }}
            >
              {isNavigating ? '🔄 规划中...' : '🧭 开始导航'}
            </button>

            {routeRef.current && (
              <button
                onClick={clearRoute}
                style={{
                  flex: 1,
                  padding: '12px 16px',
                  borderRadius: '8px',
                  border: 'none',
                  background: '#f44336',
                  color: '#fff',
                  cursor: 'pointer',
                  fontSize: '14px',
                  fontWeight: 'bold'
                }}
              >
                清除
              </button>
            )}
          </div>
        )}
      </div>

      {/* 地图容器 */}
      <div ref={mapRef} style={{ width: "100%", height: "100vh", background: "#eee" }} />
      
      {/* 自定义底部导航栏 */}
      <CustomTabBar />
    </div>
  );
};

export default Ditu;